package com.mockapi.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mockapi.entity.Route;
import com.mockapi.mapper.RouteMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 路由服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class RouteService {

    private final RouteMapper routeMapper;

    /**
     * 分页查询路由
     */
    public Page<Route> page(Integer pageNum, Integer pageSize, String name, String path, String method) {
        LambdaQueryWrapper<Route> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(name), Route::getName, name)
                .like(StrUtil.isNotBlank(path), Route::getPath, path)
                .eq(StrUtil.isNotBlank(method), Route::getMethod, method)
                .orderByDesc(Route::getPriority)
                .orderByDesc(Route::getCreatedAt);
        
        return routeMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
    }

    /**
     * 查询所有启用的路由
     */
    public List<Route> listEnabled() {
        LambdaQueryWrapper<Route> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Route::getEnabled, true)
                .orderByDesc(Route::getPriority)
                .orderByDesc(Route::getCreatedAt);
        
        return routeMapper.selectList(wrapper);
    }

    /**
     * 根据ID查询路由
     */
    public Route getById(Long id) {
        return routeMapper.selectById(id);
    }

    /**
     * 保存路由
     */
    public boolean save(Route route) {
        return routeMapper.insert(route) > 0;
    }

    /**
     * 更新路由
     */
    public boolean update(Route route) {
        return routeMapper.updateById(route) > 0;
    }

    /**
     * 删除路由
     */
    public boolean delete(Long id) {
        return routeMapper.deleteById(id) > 0;
    }

    /**
     * 根据路径和方法查找匹配的路由
     */
    public Route findMatchingRoute(String path, String method) {
        LambdaQueryWrapper<Route> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Route::getEnabled, true)
                .eq(Route::getMethod, method)
                .orderByDesc(Route::getPriority)
                .orderByDesc(Route::getCreatedAt);
        
        List<Route> routes = routeMapper.selectList(wrapper);
        
        // 按优先级排序，找到第一个匹配的路由
        return routes.stream()
                .filter(route -> isPathMatch(route.getPath(), path))
                .findFirst()
                .orElse(null);
    }

    /**
     * 获取路由总数
     */
    public long getCount() {
        return routeMapper.selectCount(null);
    }

    /**
     * 获取所有路由
     */
    public List<Route> getAllRoutes() {
        LambdaQueryWrapper<Route> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Route::getCreatedAt);
        return routeMapper.selectList(wrapper);
    }

    /**
     * 检查路径是否匹配
     */
    private boolean isPathMatch(String routePath, String requestPath) {
        // 简单的路径匹配逻辑，支持通配符
        if (routePath.equals(requestPath)) {
            return true;
        }
        
        // 支持路径参数匹配，如 /api/users/{id} 匹配 /api/users/123
        String[] routeParts = routePath.split("/");
        String[] requestParts = requestPath.split("/");
        
        if (routeParts.length != requestParts.length) {
            return false;
        }
        
        for (int i = 0; i < routeParts.length; i++) {
            String routePart = routeParts[i];
            String requestPart = requestParts[i];
            
            if (routePart.startsWith("{") && routePart.endsWith("}")) {
                // 路径参数，匹配任意值
                continue;
            }
            
            if (!routePart.equals(requestPart)) {
                return false;
            }
        }
        
        return true;
    }
} 